package lg.minecraft.plugin.pokemonmenu.gui;

import com.cobblemon.mod.common.pokemon.Pokemon;
import lg.minecraft.plugin.library.inventory.CancelInventoryContext;
import lg.minecraft.plugin.library.inventory.ClickInventoryContext;
import lg.minecraft.plugin.library.inventory.InventoryContext;
import lg.minecraft.plugin.library.inventory.LGInventory;
import lg.minecraft.plugin.pokemonmenu.LGPokemonMenu;
import lg.minecraft.plugin.pokemonmenu.PokemonPlayer;
import lg.minecraft.plugin.pokemonmenu.manager.PokemonPlayerManger;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

/**
 * @author langle__
 * @version 1.0
 */
public class ViewPartyInventor extends LGInventory {

    private static final int[] POKEMON_ARRAY = {11, 13, 15, 29, 31, 33};
    private static final int[] GLASS_ARRAY = {0, 8, 9, 17, 18, 26, 27, 35, 36, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53};

    private final Pokemon[] pokemonArray;

    public ViewPartyInventor(Pokemon[] pokemon_array) {
        super(6, LGPokemonMenu.getMessage().getGuiTitleViewParty());
        this.pokemonArray = pokemon_array;
    }

    @Override
    public void onInventoryOpen(CancelInventoryContext context) {
        for (int i = 0; i < 6; i++) {
            int slot = POKEMON_ARRAY[i];
            Pokemon pokemon = pokemonArray[i];
            ItemStack item = pokemon == null ? LGPokemonMenu.getGuiItem().getAirPoke() : LGPokemonMenu.getGuiItem().getViewPokemon(pokemon);
            inventory.setItem(slot, item);
        }
        for (int slot : GLASS_ARRAY) {
            inventory.setItem(slot, LGPokemonMenu.getGuiItem().getBorder());
        }
    }

    @Override
    public void onInventoryClick(ClickInventoryContext context) {
        context.setCancelled(true);
        Player player = context.getPlayer();
        int slot = context.getSlot();
        PokemonPlayer pokemonPlayer = PokemonPlayerManger.INSTANCE.getPokemonPlayer(player.getUniqueId());

        int pokemonSlot = slotToPokemonSlot(slot);
        if (pokemonSlot >= 0) {
            Pokemon pokemon = pokemonArray[pokemonSlot];
            if (pokemon != null) {
                pokemonPlayer.setPreviousInventory(this);
                new ViewPokemonInventory(pokemon).openInventory(player);
                player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 0.5F, 1F);
            }
        }
    }

    @Override
    public void onInventoryClose(InventoryContext context) {
    }

    private int slotToPokemonSlot(int slot) {
        for (int i = 0; i < POKEMON_ARRAY.length; i++) {
            if (POKEMON_ARRAY[i] == slot) {
                return i;
            }
        }
        return -1;
    }

}
